import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/modules/login/domain/states/login_state.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

// 普通的 Notifier ：生命周期跟 Provider 容器绑定，不会自动销毁。
// 自动销毁的 AutoDisposeNotifier ：支持自动释放，用于 NotifierProvider.autoDispose
abstract class LoginNotifier<T extends LoginState>
    extends AutoDisposeNotifier<T> {
  void setIdle() {
    state =
        state.copyWith(
              status: CommonNetStatus.idle,
              version: state.version + 1,
              agreed: state.agreed,
              message: null,
              errorCode: null,
            )
            as T;
  }

  bool agreed() => state.agreed;
  void setAgree(bool val) {
    state = state.setAgree(val) as T;
  }

  bool isLoading() {
    return state.status == CommonNetStatus.loading;
  }

  void setLoading() {
    state =
        state.copyWith(
              status: CommonNetStatus.loading,
              version: state.version + 1,
              agreed: state.agreed,
              message: null,
              errorCode: null,
            )
            as T;
  }

  void setSuccess([String? msg]) {
    state =
        state.copyWith(
              status: CommonNetStatus.success,
              message: msg,
              version: state.version + 1,
              agreed: state.agreed,
              errorCode: null,
            )
            as T;
  }

  void setFailure({String? errorCode, required String msg}) {
    state =
        state.copyWith(
              status: CommonNetStatus.failure,
              message: msg,
              version: state.version + 1,
              agreed: state.agreed,
              errorCode: errorCode,
            )
            as T;
  }

  String getErrorMessage(dynamic e) {
    if (e is String) return e;
    if (e is Error) return e.toString();
    if (e is BusinessException) {
      return e.msg;
    }
    if (e is Exception && e.toString().isNotEmpty) {
      // 对于常见异常类型，可以提取更友好的消息
      return e.toString().replaceFirst(RegExp(r'^Exception: '), '');
    }
    return '发生未知错误';
  }
}



// 是否同意用户协议，隐私政策
final agreementedProvider = StateProvider<bool>((ref) => false);
